<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span><i class="el-icon-money"></i> 收费站工作台</span>
      </div>
    </template>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">

      <el-tab-pane label="入院缴押金" name="deposit">
        <el-form :inline="true" :model="depositSearch" @submit.prevent="handleDepositSearch">
          <el-form-item label="病人姓名">
            <el-input v-model="depositSearch.patientName" placeholder="输入病人姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleDepositSearch">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="depositData" v-loading="depositLoading" style="width: 100%">
          <el-table-column prop="id" label="申请ID" width="80" />
          <el-table-column prop="patientName" label="病人姓名" width="120" />
          <el-table-column prop="doctorName" label="申请医生" width="120" />
          <el-table-column prop="departmentName" label="申请科室" width="150" />
          <el-table-column prop="iaDate" label="申请日期" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default>
              <el-tag type="danger">待缴押金</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" min-width="150">
            <template #default="scope">
              <el-button
                  size="small"
                  type="success"
                  @click="handlePayClick(scope.row)"
              >
                缴纳押金
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            style="margin-top: 20px;"
            v-model:current-page="depositPagination.pageNum"
            v-model:page-size="depositPagination.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="depositPagination.total"
            @size-change="handleDepositSizeChange"
            @current-change="handleDepositPageChange"
        />
      </el-tab-pane>

      <el-tab-pane label="出院结算（多退少补）" name="settle">
        <el-form :inline="true" :model="settleSearch" @submit.prevent="handleSettleSearch">
          <el-form-item label="病人姓名">
            <el-input v-model="settleSearch.patientName" placeholder="输入病人姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSettleSearch">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="settleData" v-loading="settleLoading" style="width: 100%">
          <el-table-column prop="id" label="申请ID" width="80" />
          <el-table-column prop="patientName" label="病人姓名" width="120" />
          <el-table-column prop="doctorName" label="申请医生" width="120" />
          <el-table-column prop="departmentName" label="所在科室" width="150" />
          <el-table-column prop="oaDate" label="申请日期" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default>
              <el-tag type="warning">待结算</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" min-width="150">
            <template #default="scope">
              <el-button
                  size="small"
                  type="danger"
                  @click="handleSettleClick(scope.row)"
              >
                办理结算
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            style="margin-top: 20px;"
            v-model:current-page="settlePagination.pageNum"
            v-model:page-size="settlePagination.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="settlePagination.total"
            @size-change="handleSettleSizeChange"
            @current-change="handleSettlePageChange"
        />
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="depositDialogVisible" title="缴纳住院押金" width="40%">
      <el-form :model="depositForm" ref="depositFormRef" label-width="100px">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="病人姓名">{{ currentDepositApp.patientName }}</el-descriptions-item>
          <el-descriptions-item label="申请科室">{{ currentDepositApp.departmentName }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="缴纳金额" prop="amount" :rules="[{ required: true, message: '金额不能为空' }]" style="margin-top: 20px;">
          <el-input-number
              v-model="depositForm.amount"
              :min="1000"
              :precision="2"
              controls-position="right"
              style="width: 100%;"
          />
          <el-alert title="根据医院规定，住院押金至少缴纳1000元" type="info" show-icon :closable="false" style="margin-top: 5px;"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="depositDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDepositPayment">确认缴费</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
// 1. 引入 Element Plus 的消息组件
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listPendingDeposits,
  listPendingSettlements,
  payInpatientDeposit,
  settleDischarge
} from '../api/finance.js';

export default {
  name: "BillingStation",
  // 3. 定义 data
  data() {
    return {
      activeTab: 'deposit', // 默认激活 "入院缴押金"

      // 入院押金 Tab
      depositSearch: {
        patientName: ''
      },
      depositData: [],
      depositLoading: false,
      depositPagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      depositDialogVisible: false,
      currentDepositApp: {}, // 当前操作的申请单
      depositForm: {
        amount: 1000.00
      },

      // 出院结算 Tab
      settleSearch: {
        patientName: ''
      },
      settleData: [],
      settleLoading: false,
      settlePagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    };
  },

  // 4. 定义 methods
  methods: {
    // --- 通用方法 ---
    handleTabClick(tab) {
      if (tab.paneName === 'deposit' && this.depositData.length === 0) {
        this.fetchDepositData();
      } else if (tab.paneName === 'settle' && this.settleData.length === 0) {
        this.fetchSettleData();
      }
    },

    // --- 1. 入院押金 Methods ---
    async fetchDepositData() {
      this.depositLoading = true;
      try {
        const query = {
          ...this.depositSearch,
          pageNum: this.depositPagination.pageNum,
          pageSize: this.depositPagination.pageSize
        };
        // (后端需要您新建此API)
        const { data: response } = await listPendingDeposits(query);
        if (response.code === 200) {
          this.depositData = response.obj.list;
          this.depositPagination.total = response.obj.total;
        } else {
          this.depositData = [];
          this.depositPagination.total = 0;
        }
      } catch (error) {
        ElMessage.error('加载待缴费列表失败');
      } finally {
        this.depositLoading = false;
      }
    },
    handleDepositSearch() {
      this.depositPagination.pageNum = 1;
      this.fetchDepositData();
    },
    handleDepositSizeChange(val) {
      this.depositPagination.pageSize = val;
      this.fetchDepositData();
    },
    handleDepositPageChange(val) {
      this.depositPagination.pageNum = val;
      this.fetchDepositData();
    },

    // 点击 "缴纳押金" 按钮
    handlePayClick(row) {
      this.currentDepositApp = { ...row };
      this.depositForm.amount = 1000.00; // 重置金额
      this.depositDialogVisible = true;
    },

    // 弹窗中 "确认缴费"
    submitDepositPayment() {
      this.$refs.depositFormRef.validate(async (valid) => {
        if (valid) {
          if (this.depositForm.amount < 1000) {
            ElMessage.warning('住院押金至少为1000元');
            return;
          }

          try {
            const data = {
              applicationId: this.currentDepositApp.id,
              patientId: this.currentDepositApp.patientId,
              amount: this.depositForm.amount
            };

            // 调用创建的API
            const { data: response } = await payInpatientDeposit(data);

            if (response.code === 200) {
              ElMessage.success('押金缴纳成功！');
              this.depositDialogVisible = false;
              await this.fetchDepositData(); // 刷新列表
            }
          } catch (error) {
            ElMessage.error(error.response.data.message || '缴费失败');
          }
        }
      });
    },

    // --- 2. 出院结算 Methods ---
    async fetchSettleData() {
      this.settleLoading = true;
      try {
        const query = {
          ...this.settleSearch,
          pageNum: this.settlePagination.pageNum,
          pageSize: this.settlePagination.pageSize
        };
        // (后端需要您新建此API)
        const { data: response } = await listPendingSettlements(query);
        if (response.code === 200) {
          this.settleData = response.obj.list;
          this.settlePagination.total = response.obj.total;
        } else {
          this.settleData = [];
          this.settlePagination.total = 0;
        }
      } catch (error) {
        ElMessage.error('加载待结算列表失败');
      } finally {
        this.settleLoading = false;
      }
    },
    handleSettleSearch() {
      this.settlePagination.pageNum = 1;
      this.fetchSettleData();
    },
    handleSettleSizeChange(val) {
      this.settlePagination.pageSize = val;
      this.fetchSettleData();
    },
    handleSettlePageChange(val) {
      this.settlePagination.pageNum = val;
      this.fetchSettleData();
    },

    // 点击 "办理结算" (多退少补)
    handleSettleClick(row) {
      ElMessageBox.confirm(
          `即将为病人 [${row.patientName}] 办理出院结算，请确认。`,
          '出院结算',
          {
            confirmButtonText: '开始结算',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        // (调用我们上一轮创建的API)
        try {
          const data = {
            dischargeApplicationId: row.id,
            patientId: row.patientId
          };
          const { data: response } = await settleDischarge(data);

          // (核心) 处理 "多退" 或 "结清" 的情况
          if (response.code === 200) {
            const result = response.obj;
            if (result.status === 'REFUND') {
              ElMessageBox.alert(`结算成功！请退还患者 ${result.amount} 元。`, '结算完成', { type: 'success' });
            } else if (result.status === 'SETTLED') {
              ElMessage.success('结算成功！押金正好用完。');
            }
            await this.fetchSettleData(); // 刷新列表
          }

        } catch (error) {
          // (核心) 处理 "少补" (欠费) 的情况
          const responseData = error.response.data;
          if (responseData && responseData.obj && responseData.obj.status === 'OWES') {
            ElMessageBox.alert(`结算失败！患者尚欠费 ${responseData.obj.amount} 元。请患者补缴费用后，再重新点击“办理结算”按钮。`, '结算失败 (欠费)', { type: 'error' });
          } else {
            ElMessage.error(responseData.message || '结算失败，请重试');
          }
        }
      }).catch(() => {
        // 用户点击了取消
      });
    }
  },

  // 5. 定义 created 钩子
  created() {
    // 页面加载时，自动获取第一个Tab的数据
    this.fetchDepositData();
  }
}
</script>

<style scoped>
/* (您可以添加自定义样式，或复用 InpatientApplicationList.vue 的样式) */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.el-form {
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 20px;
}
</style>